/**
 * Licensed under The MIT License
 *  Copyright (c) 2011 Han Wen
 *  
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 **/

package edu.rochester.URshuttleschedule;

import java.util.Calendar;

import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;

public class URshuttleschedule extends TabActivity implements
		OnTabChangeListener {
	public static final String PREFS_NAME = "URSSPrefFile";
	public static String indicator;
	public static int lineCode;
	private static String myLocation;
	public static int[] listDividerColor;
	private final Calendar c = Calendar.getInstance();
	private TabSpec firstTabSpec;
	private TabSpec secondTabSpec;
	private TabHost tabHost;
	private static int schedule[] = { 0, 0 };
	private static int station[] = { 0, 0 };
	private static int isDirect[] = { 0, 0 };
	public static int stationIndex = 0;

	private Menu menuHandler; // use for changing menu from submenu item

	private static boolean locationChanged = false;
	private static boolean lineChanged = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab);
		tabHost = (TabHost) findViewById(android.R.id.tabhost);
		firstTabSpec = tabHost.newTabSpec("dir1");
		secondTabSpec = tabHost.newTabSpec("dir2");
		SharedPreferences settings = getSharedPreferences(PREFS_NAME,
				Activity.MODE_PRIVATE);
		lineCode = settings.getInt("LineColor", 1);
		myLocation = settings.getString("Location", "Rush Rhees");
		stationIndex = settings.getInt("StationIndex", 0);
		indicator = PreferenceManager.getDefaultSharedPreferences(
				getBaseContext()).getString("indicator", "orz");
		setTitle("From  " + myLocation);
		Bundle bundle = new Bundle();
		String tabTitle[] = chooseData();
		Intent ntab = new Intent(this, OverView.class);
		bundle.putInt("TabId", 0);
		ntab.putExtras(bundle);
		firstTabSpec.setIndicator(tabTitle[0]).setContent(ntab);
		ntab = new Intent(this, OverView.class);
		bundle = new Bundle();
		bundle.putInt("TabId", 1);
		ntab.putExtras(bundle);
		secondTabSpec.setIndicator(tabTitle[1]).setContent(ntab);
		tabHost.addTab(firstTabSpec);
		tabHost.addTab(secondTabSpec);
		tabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 50;
		tabHost.getTabWidget().getChildAt(1).getLayoutParams().height = 50;
		tabHost.setOnTabChangedListener(this);
	}

	private String[] chooseData() {
		String tabTitle[] = new String[2];
		int date = c.get(Calendar.DAY_OF_WEEK);
		switch (lineCode) {
		case 1: // blue line
		default: // default to blue line
			if (Calendar.SATURDAY == date) {
				schedule[0] = R.array.blue2RRLSat;
				station[1] = R.array.blue2WPPStationsSunSat;
				schedule[1] = R.array.blue2WPPSat;
			} else {
				if (Calendar.SUNDAY == date) {
					schedule[0] = R.array.blue2RRLSun;
					station[1] = R.array.blue2WPPStationsSunSat;
					schedule[1] = R.array.blue2WPPSun;
				} else {
					schedule[0] = R.array.blue2RRL;
					station[1] = R.array.blue2WPPStations;
					schedule[1] = R.array.blue2WPP;
				}
			}
			tabTitle[0] = "To Rush Rhees";
			tabTitle[1] = "To Whipple Park";
			// Same stations list every day. May not be true in the future.
			station[0] = R.array.blue2RRLStations; 
			listDividerColor = new int[] { 0xFF007dc3, 0xff1e3eff, 0xFF007dc3 };
			isDirect[0] = R.array.isbluedirect2RRL;
			isDirect[1] = R.array.isbluedirect2WPP;
			break;
		case 2: // red line
			switch (date) {
			case Calendar.TUESDAY:
			case Calendar.THURSDAY:
				schedule[0] = R.array.red2RRLTueThur;
				schedule[1] = R.array.red2ELCTueThur;
				station[0] = R.array.red2RRLStations;
				station[1] = R.array.red2ELCStations;
				break;
			case Calendar.SUNDAY:
				schedule[0] = R.array.red2RRLSun;
				schedule[1] = R.array.red2ELCSun;
				station[0] = R.array.red2RRLStationsSun;
				station[1] = R.array.red2ELCStationsSun;
				break;
			case Calendar.SATURDAY:
				schedule[0] = R.array.red2RRLSat;
				schedule[1] = R.array.red2ELCSat;
				station[0] = R.array.red2RRLStationsSat;
				station[1] = R.array.red2ELCStationsSat;
				break;
			default:
				schedule[0] = R.array.red2RRL;
				schedule[1] = R.array.red2ELC;
				station[0] = R.array.red2RRLStations;
				station[1] = R.array.red2ELCStations;
			}
			tabTitle[0] = "To Rush Rhees";
			tabTitle[1] = "To Eastman Living Center";
			listDividerColor = new int[] { 0xFFf9d1d3, 0xffff9193, 0xFFf9d1d3 };
			break;
		case 3: // gold line
			switch (date) {
			case Calendar.THURSDAY:
			case Calendar.FRIDAY:
				schedule[0] = schedule[1] = R.array.goldThur2Fri;
				isDirect[0] = isDirect[1] = R.array.isgolddirectThur2Fri;
				break;
			case Calendar.SATURDAY:
			case Calendar.SUNDAY:
				schedule[0] = schedule[1] = R.array.goldSat2Sun;
				break;
			default:
				schedule[0] = schedule[1] = R.array.goldMon2Wed;
				isDirect[0] = isDirect[1] = R.array.isgolddirectMon2Wed;
			}
			station[0] = station[1] = R.array.goldStations;
			tabTitle[0] = "Gold";
			tabTitle[1] = "Line";
			listDividerColor = new int[] { 0xFFffcf01, 0xffffff01, 0xFFffcf01 };
			break;
		case 4: // green line
			switch (date) {
			case Calendar.TUESDAY:
			case Calendar.WEDNESDAY:
				schedule[0] = R.array.green2RRLTueWed;
				schedule[1] = R.array.green2WMTueWed;
				station[0] = R.array.green2RRLStationsTueWed;
				station[1] = R.array.green2WMStationsTueWed;
				tabTitle[0] = "To Rush Rhees";
				tabTitle[1] = "To Wal-Mart";
				break;
			case Calendar.SATURDAY:
				schedule[0] = R.array.green2RRLSat;
				schedule[1] = R.array.green2PMSat;
				station[0] = R.array.green2RRLStationsSat;
				station[1] = R.array.green2PMStationsSat;
				tabTitle[0] = "To Rush Rhees/Marketplace";
				tabTitle[1] = "To Public Market/Marketplace";
				isDirect[0] = R.array.isgreenmarketplace2RRL;
				isDirect[1] = R.array.isgreenmarketplace2PM;
				break;
			case Calendar.SUNDAY:
				schedule[0] = R.array.green2RRLSun;
				schedule[1] = R.array.green2PPSun;
				station[0] = R.array.green2RRLStationsSun;
				station[1] = R.array.green2PPStationsSun;
				tabTitle[0] = "To Rush Rhees";
				tabTitle[1] = "To Pittsford Plaza";
				break;
			default: // no green line available
				schedule[0] = schedule[1] = station[0] = station[1] = R.array.nullArray;
				tabTitle[0] = tabTitle[1] = "Not available";
			}
			listDividerColor = new int[] { 0xff00a94f, 0xff1eff1e, 0xff00a94f };
			break;
		}
		return tabTitle;
	}

	public static int getStation(int TabId) {
		return station[TabId];
	}

	public static int getSchedule(int TabId) {
		return schedule[TabId];
	}

	public static String getMyLocation() {
		return myLocation;
	}

	public static int getIsDirect(int TabId) {
		return isDirect[TabId];
	}
	
	@Override
	protected void onStop() {
		super.onStop();

		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("LineColor", lineCode);
		editor.putString("Location", myLocation);
		editor.putInt("StationIndex", stationIndex);
		editor.commit();
	}

	public void changeLine() {
		String tabTitle[] = chooseData();
		// hacky way to change tab indicator
		TabWidget tabWgt = getTabWidget();
		((TextView) ((RelativeLayout) tabWgt.getChildAt(0)).getChildAt(1))
				.setText(tabTitle[0]);
		((TextView) ((RelativeLayout) tabWgt.getChildAt(1)).getChildAt(1))
				.setText(tabTitle[1]);
		((OverView) getLocalActivityManager().getActivity(
				tabHost.getCurrentTabTag())).reload();
		menuHandler.removeItem(2011);
		setupSubmenu(menuHandler);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mainmenu, menu);
		menu.getItem(0).getSubMenu().getItem(URshuttleschedule.lineCode - 1)
				.setChecked(true); // restore the checked item
		setupSubmenu(menu);
		menuHandler = menu;
		return true;
	}

	private void setupSubmenu(Menu menu) {
		int menuRes;
		switch (URshuttleschedule.lineCode) {
		case 1: // blue
		default:
			menuRes = R.menu.bluestation;
			break;
		case 2: // red
			menuRes = R.menu.redstation;
			break;
		case 3: // gold
			menuRes = R.menu.goldstation;
			break;
		case 4: // green
			menuRes = R.menu.greenstation;
			break;
		}
		SubMenu submenu = menu.addSubMenu(0, 2011, 1, "Location").setIcon(
				R.drawable.ic_menu_mylocation);
		getMenuInflater().inflate(menuRes, submenu);
		submenu.getItem(stationIndex).setChecked(true);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getGroupId()) {
		case R.id.lines:
			if (item.getOrder() == lineCode) // nothing changed
				return true;
			lineCode = item.getOrder();
			changeLine();
			lineChanged = true;
			break;
		case R.id.blueStation:
		case R.id.redStation:
		case R.id.greenStation:
		case R.id.goldStation:
			String selection = (String) item.getTitle(); // availLocation[item.getOrder()]
			if (myLocation.equals(selection)) // nothing changed
				return true;
			stationIndex = item.getOrder();
			OverView tab = (OverView) getLocalActivityManager().getActivity(
					tabHost.getCurrentTabTag());
			tab.changeLocation(selection);
			locationChanged = true;
			myLocation = selection;
			setTitle("From  " + myLocation);
			break;
		default:
			if (item.getItemId() == R.id.setting)
				startActivity(new Intent(getBaseContext(), Preferences.class));
			return super.onOptionsItemSelected(item);
		}
		if (item.isChecked())
			item.setChecked(false);
		else
			item.setChecked(true);
		return true;
	}

	@Override
	public void onTabChanged(String tabId) {
		if (locationChanged) {
			OverView tab = (OverView) getLocalActivityManager().getActivity(
					tabHost.getCurrentTabTag());
			tab.changeLocation(myLocation);
			locationChanged = false;
		}
		if (lineChanged) {
			OverView tab = (OverView) getLocalActivityManager().getActivity(
					tabHost.getCurrentTabTag());
			tab.reload();
			lineChanged = false;
		}
	}
}
